package main.java.com.amanda.suafa;

import edu.princeton.cs.algs4.Queue;

/**
 * @author amanda
 * @Description
 * 使用散列的查找算法分为两步，第一步是用散列函数将被查找的键转化为数组的一个索引
 * 第二步就是一个处理碰撞冲突的过程（拉链法和线性探测法）
 *
 * 算法3.5 基于拉链法的散列表
 * 两步：1、首先根据散列值找到对应的链表
 *      2、沿着链表顺序查找相应的键
 */
public class SeparateChainingHashST<Key, Value> {

    private static final int INIT_CAPACITY = 4;
    private int N;
    private int M;
    private SequentialSearchST<Key, Value>[] st;
    public SeparateChainingHashST() {
        this(INIT_CAPACITY);
    }
    public SeparateChainingHashST(int M) {
        this.M = M;
        st = (SequentialSearchST<Key, Value>[]) new SequentialSearchST[M];
        for (int i = 0; i < M; i++)
            st[i] = new SequentialSearchST<>();
    }
    public int size() {
        return N;
    }
    public boolean isEmpty() {
        return size() == 0;
    }

    private int hash(Key  key) {
        return (key.hashCode() & 0x7fffffff) % M;
    }
    /*private int hash(Key key) {
        int h = key.hashCode();
        h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
        return h & (m-1);
    }*/
    private int hashTextbook(Key key) {
        return (key.hashCode() & 0x7fffffff) % M;
    }

    public Value get(Key key) {
        if (key == null)
            throw new IllegalArgumentException("argument to get() is null");
        return (Value) st[hash(key)].get(key);
    }
    public boolean contains(Key key) {
        if (key == null)
            throw new IllegalArgumentException("argument to contains() is null");
        return get(key) != null;
    }
    public void put(Key key, Value val) {
        if (key == null)
            throw new IllegalArgumentException("first argument to put() is null");
        if (val == null) {
            delete(key);
            return;
        }
        if (N >= 10*M)
            resize(2*M);
        st[hash(key)].put(key, val);
    }
    public void delete(Key key) {
        if (key == null)
            throw new IllegalArgumentException("argument to delete() is null");
        int i = hash(key);
        if (st[i].contains(key))
            N--;
        st[i].delete(key);
        if (M > INIT_CAPACITY && N <= 2*M)
            resize(M/2);
    }

    public Iterable<Key> keys() {
        Queue<Key> queue = new Queue<Key>();
        for (int i = 0; i < M; i++) {
            for (Key key : st[i].keys())
                queue.enqueue(key);
        }
        return queue;
    }
    private void resize(int chains) {
        SeparateChainingHashST<Key, Value> temp = new SeparateChainingHashST<Key, Value>(chains);
        for (int i = 0; i < M; i++) {
            for (Key key : st[i].keys()) {
                temp.put(key, st[i].get(key));
            }
        }
        this.M  = temp.M;
        this.N  = temp.N;
        this.st = temp.st;
    }
}
